<?php
/**
 * @author spenceryg
 * @date 2022/4/11
 * @time 11:00 上午
 * @focus love & life
 */


namespace app\wechat\service;

//'ToUserName' => 'gh_936407cb9f8d',
//  'FromUserName' => 'ocNmM6jr1zgemA6rtCJt8eni90j0',
//  'CreateTime' => '1649644748',
//  'MsgType' => 'event',
//  'Event' => 'SCAN',
//  'EventKey' => 'foo',
//  'Ticket' => 'gQGi7zwA
//
use app\common\model\Member;
use app\wechat\model\WechatLogin;
use EasyWeChat\Factory;
use think\facade\Log;

class WechatLoginService
{
    public static function addRecord(array $data)
    {
        Log::record($data);

        if ($data['Event'] == 'SCAN' || $data['Event'] == 'subscribe') {

            if (strpos($data['EventKey'], 'unbind_') === 0) {
                $member_id = (int)str_replace('unbind_', '', $data['EventKey']);
                $find = Member::where('id', $member_id)->where('official_openid', $data['FromUserName'])->find();
                if ($find) {
                    Member::where('id', $member_id)->where('official_openid', $data['FromUserName'])->save(['official_openid' => null]);
                    $add = [];
                    $add['scene'] = str_replace('qrscene_', '' ,$data['EventKey']);
                    $add['union_id'] = $data['FromUserName'];
                    WechatLogin::create($add);
                    return '解除绑定成功！';
                } else {
                    return '扫码微信并非当前账号绑定微信，请用绑定微信扫码解绑!';
                }
            }
            elseif (strpos($data['EventKey'], 'bind_') === 0) {
                $member_id = (int)str_replace('bind_', '', $data['EventKey']);
                $config = [
                    'app_id' => config('wechat_official_account.app_id'),
                    'secret' => config('wechat_official_account.secret'),
                    'response_type' => 'array',
                ];
                $app = Factory::officialAccount($config);
                $union_id = $app->user->get($data['FromUserName'])['unionid'];
                Member::where('id', $member_id)->save([
                    'official_openid' => $data['FromUserName'],
                    'union_id' => $union_id
                ]);
                $add = [];
                $add['scene'] = str_replace('qrscene_', '' ,$data['EventKey']);
                $add['union_id'] = $data['FromUserName'];
                WechatLogin::create($add);
                return '绑定微信账号成功！';
             }
            else {
                $add = [];
                $add['scene'] = str_replace('qrscene_', '' ,$data['EventKey']);
                $add['union_id'] = $data['FromUserName'];

                $config = [
                    'app_id' => config('wechat_official_account.app_id'),
                    'secret' => config('wechat_official_account.secret'),
                    'response_type' => 'array',
                ];
                $app = Factory::officialAccount($config);
                $user = $app->user->get($data['FromUserName']);
                $unionid = $user['unionid'];
                if($unionid){
                    $member = Member::where('union_id', $unionid)->find();
                    if($member){
                        $member->official_openid = $user['openid'];
                        $member->save();
                    }
                }
                file_put_contents('user.txt', json_encode($user));

                WechatLogin::create($add);
                return '';
            }


        }


    }

    public static function getLastSceneData(string $scene)
    {
       return  $res = WechatLogin::where('scene', $scene)->where('create_time', '>', time() - 20)->order('id desc')->find();
    }


}
